<template>
  <div class="swiper-container" v-if="bannerArr.length">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="(item, index) in bannerArr" :key="index">
        <div v-if="item.image">
          <router-link v-if="item.link" :to="item.link">
            <img :src="item.image" :title="item.title" @load="imgLoad" />
          </router-link>
          <router-link v-else tag="div">
            <img :src="item.image" :title="item.title" @load="imgLoad" />
          </router-link>
        </div>
        <div v-else>
          <img :src="item" :title="item" @load="imgLoad" />
        </div>
      </div>
    </div>
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>
    <div class="swiper-pagination"></div>
  </div>
</template>
<script>
import Swiper from "swiper";
import "swiper/css/swiper.min.css";

export default {
  name: "swiper",
  props: {
    banners: {
      type: Array,
    },
  },
  data() {
    return {
      isLoad: false,
    };
  },
  computed: {
    bannerArr() {
      this.bannerSwiper();
      return this.banners;
    },
  },
  methods: {
    // 需要在数据更新之后调用
    bannerSwiper() {
      this.$nextTick(() => {
        new Swiper(".swiper-container", {
          autoplay: {
            delay: 2000, //1秒切换一次
          },
          loop: true,
          navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
          },
          pagination: {
            el: ".swiper-pagination",
            clickable: true,
          },
        });
      });
    },
    imgLoad() {
      if (!this.isLoad) {
        this.$emit("swiperImgLoad");
        this.isLoad = true;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.swiper-wrapper img {
  width: 100%;
}
/* 设置前进后退 */
.swiper-container {
  --swiper-theme-color: #fff; /* 设置Swiper风格 */
  --swiper-navigation-color: #fff; /* 单独设置按钮颜色 */
  --swiper-navigation-size: 20px; /* 设置按钮大小 */
}
/* 设置分页默认样式 */
v-deep .swiper-pagination-bullet{
  background: #fff;
  opacity: 1;
}
/* 设置分页 */
.swiper-container {
  --swiper-theme-color: #ff5777;
  --swiper-pagination-color: #ff5777; /* 两种都可以 */
}
</style>

